<template>
  <view class="historyOrder">
    <view class="header" :style="{ top: stickyTop + 'px' }">
      <view class="tabs">
        <view
          :class="['tabs-item', tabIdx == item.id ? 'act' : '']"
          v-for="(item, index) in typeList"
          :key="index"
          @click="handleClickTab(item.id)"
          >{{ item.text }}</view
        >
      </view>
      <!-- 历史工单提示 -->
      <view class="historyTips">
        <view class="left">{{ title }}</view>
        <view class="right" v-if="tabIdx != 3 && tabIdx !== -1">
          <filterModel
            :all="false"
            :orderType="tabIdx"
            ref="filterModel"
            :dateOpt="dateObj"
            :csd="csd"
            :elevatorId="elevatorId"
            @filterd="filterd"
            @showFilterChange="showFilterChange"
          >
          </filterModel>
        </view>
      </view>
    </view>

    <view class="orderListMain">
      <view class="" v-if="list.length">
        <view v-if="tabIdx >= 0">
          <view class="content" v-for="(item, index) in list" :key="index">
            <view class="date">
              {{ item.planDate || "" }}
              <view class="line"></view>
            </view>
            <view>
              <order-list
                v-for="(e, i) in item.dataList"
                :key="i"
                :item="e"
                :tabIdx="tabIdx"
                :typeIdx="typeIdx"
                :parentIdx="index"
                :childIdx="i"
                @userMore="handleUserMore"
                :elevatorId="elevatorId"
                @update="restList()"
              >
              </order-list>
            </view>
          </view>
        </view>

        <view class="all" v-if="tabIdx == -1">
          <view class="year" v-for="(item, index) in list" :key="index">
            <view class="year_item">
              <view class="year_left">
                <view class="yearLabel">
                  {{ item.label }}
                </view>
              </view>

              <view class="year_right">
                <view class="list_item" v-for="(e, i) in item.value" :key="i">
                  <view class="left"
                    >{{ e.label.slice(5, 12).replaceAll("-", "/") }}
                    <view class="line"></view>
                  </view>
                  <view class="right">
                    <all-order-list
                      v-for="(v, j) in e.value"
                      :key="j"
                      :item="v"
                      @userMore="handleUserMore"
                      :elevatorId="elevatorId"
                      @update="restList()"
                    >
                    </all-order-list>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="more" v-if="tabIdx == -1" @click="handleLoadMore">
          {{ stopQuery ? "- 已经到底了 -" : "点击加载更多" }}
          <!-- <view v-show="isLoadMore"><uni-load-more :status="loadStatus"></uni-load-more></view> -->
        </view>
        <view class="more" v-if="tabIdx != -1">- 已经到底了 -</view>
      </view>

      <view class="empty" v-else>
        <view class="img">
          <image src="@/static/images/default.png"></image>
        </view>
        <view class="text">- 暂无相关数据 -</view>
      </view>
    </view>
  </view>
</template>

<script>
import filterModel from '../components/filter/index.vue';
import OrderList from '../components/eleOrderList.vue';
import AllOrderList from './components/allOrder.vue';
import dayjs from 'dayjs';
import { getNowTime, getBeforeDate } from '@/utils/utils.js';
import UniLoadMore from '@/components/uni-load-more/uni-load-more';
import {
	maintenanceHistoryTasks,
	maintenanceUnfinished,
	repairHistoryTasks,
	repairUnfinished,
	partHistoryTasks,
	partUnfinished,
	elevtorMantles,
	getElevatorOfRescueInfo,
	getAllPlanList,
} from '@/apis/elevator.js';
// 保养搜索条件
const mSearchForm = {
	startTime: '',
	endTime: '',
	timeliness: [],
	duration: [],
	templateIds: [],
	sign: [],
};
// 维修搜索条件
const wSearchForm = {
	startTime: '',
	endTime: '',
	problemItems: [],
	sign: [],
};
// 配件搜索条件
const pSearchForm = {
	startTime: '',
	endTime: '',
	partsId: [],
	sign: [],
};
// 空数据搜索条件
const emptDate = {
	startTime: '',
	endTime: '',
	value: '',
	planBeginDate: '',
	planEndDate: '',
};
export default {
	components: {
		filterModel,
		OrderList,
		AllOrderList,
	},
	props: {
		// tab的类型,全部,保养,维修,配件,救援
		// tabIdx: {
		//   type: [String, Number],
		// },
		elevatorId: {
			type: String,
		},
		stickyTop: {
			type: Number,
		},
	},
	data() {
		return {
			dateObj: {
				startTime: '',
				endTime: '',
				value: '',
				planBeginDate: '',
				planEndDate: '',
			},
			title: '', // 头部展示已完成多少单,通过接口返回展示
			csd: {},
			wxCsd: {},
			pjCsd: {},
			list: [],
			typeList: [
				{ text: '全部', id: -1 },
				{ text: '保养', id: 0 },
				{ text: '维修', id: 1 },
				{ text: '配件', id: 2 },
				{ text: '救援', id: 3 },
			],
			tabIdx: -1,

			curStarDate: new Date().getFullYear(),
			// curEedDate: dayjs().format("YYYY-MM-DD"),
			loadStatus: 'loading', // 加载样式：more-加载前样式，loading-加载中样式，noMore-没有数据样式
			isLoadMore: false,
			stopQuery: false,
		};
	},
	created() {
		this.fetchOrderList();
	},
	watch: {
		tabIdx(val) {
			this.fetchOrderList();
		},
	},
	methods: {
		handleUserMore(res) {
			const { parentIdx, childIdx, val } = res;
			// this.list[parentIdx].dataList[childIdx].usermore = val;
		},
		// 首次加载如果为空指标继续加载
		continuereQuest() {
			console.log(this.curStarDate, 'this.curStarDate');
			if (this.curStarDate < 2022) {
				console.log(this.curStarDate);
				this.stopQuery = true;
				return;
			} else {
				this.stopQuery = false;
				this.curStarDate = this.curStarDate - 1;
				console.log('继续加载', this.curStarDate);
				this.fetchOrderList();
			}
		},
		handleLoadMore() {
			if (this.stopQuery) {
				return;
			}
			this.isLoadMore = true;
			this.stopQuery = false;
			this.curStarDate = this.curStarDate - 1;
			this.fetchOrderList();
		},
		// 点击tab页面
		handleClickTab(res) {
			this.tabIdx = res;
			this.isLoadMore = false;
			this.curStarDate = new Date().getFullYear();
			this.list = [];
			this.title = '';
			this.$emit('changeTab');
			if (res !== -1) {
				// console.log("初始化筛选组件")
				this.csd = {};
				this.dateObj = Object.assign(emptDate, {});
				this.$nextTick(() => {
					try {
						this.$refs.filterModel.initModel(this.tabIdx, this.dateObj);
					} catch (error) {}
				});
			}
		},
		resetSearchForm() {
			if (this.tabIdx == 0) {
				this.mSearchForm = Object.assign(mSearchForm, {});
			}
			if (this.tabIdx == 1) {
				this.wSearchForm = Object.assign(wSearchForm, {});
			}
			if (this.tabIdx == 2) {
				this.pSearchForm = Object.assign(pSearchForm, {});
			}
		},
		// 查询列表信息
		fetchOrderList() {
			uni.showLoading({
				title: '加载中',
				mask: true,
			});

			const historyFun = [
				maintenanceHistoryTasks,
				repairHistoryTasks,
				partHistoryTasks,
				getElevatorOfRescueInfo,
			];
			const historyParams = [
				this.mSearchForm,
				this.wSearchForm,
				this.pSearchForm,
				{ type: 2 },
			];
			if (this.tabIdx >= 0) {
				this.list = [];
				historyFun[this.tabIdx]({
					elevatorId: this.elevatorId,
					...historyParams[this.tabIdx],
				}).then((res) => {
					if (res) {
						uni.hideLoading();
						this.title = res.data.title;
						const records = res.data.list || [];
						records.forEach((item, index) => {
							for (let i = 0; i < item.dataList.length; i++) {
								item.dataList[i].usermore = false;
								if (item.dataList[i].partsName != null) {
									const parts = item.dataList[i].partsName.split('&amp;&amp;');
									item.dataList[i].parts = parts[parts.length - 1];
								}
							}
						});
						this.list = records;
						console.log('records', records);
						this.isCanScroll = this.list.length ? true : false;
					}
				});
			} else {
				// 这里是全部的数据

				// if (!this.isLoadMore) {
				//   this.list = [];
				//   this.curStarDate = new Date().getFullYear()
				// }
				const parsms = {
					elevatorId: this.elevatorId,
					startDate: this.curStarDate + '-01-01 00:00:00',
					endDate: this.curStarDate + '-12-31 23:59:59',
				};
				getAllPlanList(parsms).then((res) => {
					if (res.data.value.length == 0) {
						// 如果是加载更多
						if (this.isLoadMore) {
							uni.hideLoading();
							this.title = res.data.label;
							this.stopQuery = true;
							return;
						} else {
							// 如果是首次加载
							this.list = [];
							this.continuereQuest();
						}
					}
					this.title = res.data.label;
					this.list.push(...res.data.value);
					uni.hideLoading();
				});
			}
		},
		// 接收到的筛选后的数据
		filterd(res) {
			console.log(res, '最外层父组件');
			let {
				choosed,
				dateObj: { startTime, endTime, planBeginDate, planEndDate },
			} = res;
			let dateObj = res.dateObj;
			this.csd = choosed;
			console.log(res, dateObj, '最外层父组件');
			let map = {
				0: this.mSearchForm,
				1: this.wSearchForm,
				2: this.pSearchForm,
			};

			if (this.tabIdx == 0) {
				this.mSearchForm = {};
				this.mSearchForm = {
					...choosed,
					startTime,
					endTime,
					planBeginDate,
					planEndDate,
				};
				this.csd = choosed;
				this.dateObj = dateObj;
			} else if (this.tabIdx == 1) {
				this.wSearchForm = {};
				(this.wSearchForm = {
					...choosed,
					startTime,
					endTime,
					planBeginDate,
					planEndDate,
				}),
				(this.dateObj = dateObj);
			} else {
				this.pSearchForm = {};
				(this.pSearchForm = {
					...choosed,
					startTime,
					endTime,
					planBeginDate: planBeginDate,
					planEndDate: planEndDate,
				}),
				(this.dateObj = dateObj);
			}

			this.fetchOrderList();
		},
		showFilterChange(res) {
			this.$emit('showFilterChange', res);
			this.isCanScroll = !res;
		},
	},
};
</script>

<style lang="scss" scoped>
.historyOrder {
  .header {
    position: sticky;
    // top: 0;
    left: 0;
    z-index: 10;
  }
  .tabs {
    background-color: #ffffff;
    display: flex;
    // border-bottom: 2rpx #eee solid;
    height: 76rpx;
    padding: 0 22rpx;
    align-items: center;
    justify-content: space-between;

    &-item {
      display: flex;
      width: 128rpx;
      height: 44rpx;
      background: #f3f6f8;
      border-radius: 22rpx;
      font-size: 26rpx;
      font-weight: 400;
      // border-bottom: 4rpx solid #fff;
      color: #666;
      transition: 0.4s all;
      justify-content: center;
      align-items: center;
    }

    .act {
      color: #0091ff;
      background: #dcf0ff;
    }
  }
  .historyTips {
    background-color: #f3f6f8;
    color: #666;
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    .right {
      width: 300rpx;
    }
  }
  .orderListMain {
    background: #f3f6f8;
    .content_Tit {
      display: flex;
      justify-content: space-between;

      .date_count {
        font-size: 24rpx;
        color: #666666;
        margin-right: 20rpx;

        text {
          color: #0091ff;
        }
      }
    }

    .date {
      color: #333;
      font-size: 26rpx;
      font-weight: 600;
      padding-left: 40rpx;
      position: relative;
    }

    .line {
      width: 4rpx;
      height: 22rpx;
      background: #333333;
      position: absolute;
      left: 20rpx;
      top: 8rpx;
    }

    .more {
      width: 100%;
      padding: 30rpx 0;
      text-align: center;
      color: #999999;
      font-size: 24rpx;
    }
  }
  .empty {
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 64rpx;
      height: 64rpx;
    }

    height: 800rpx;
    flex-direction: column;
  }
  .year {
    width: 100%;
    .year_item {
      display: flex;
      position: relative;

      .year_left {
        position: absolute;
        left: 15rpx;
        font-size: 28rpx;
        top: 18rpx;
        display: flex;
        .title {
          color: #666;
          font-size: 26rpx;
          padding-left: 42rpx;
        }
      }
      .year_right {
        display: flex;
        flex-direction: column;
        flex: 1;
        margin-top: 60rpx;
      }
    }
  }
  .list {
    width: 100%;
    position: relative;
  }
  .list_item {
    display: flex;
    width: 100%;
    position: relative;

    .left {
      position: relative;
      left: 14rpx;
      width: 110rpx;
      top: 34rpx;
      font-size: 26rpx;
      font-weight: 500;
      .line {
        width: 2rpx;
        height: calc(100% - 114rpx);
        background: #d2dae0;
        position: absolute;
        left: 42rpx;
        margin: 20rpx 0;
        top: 32rpx;
      }
    }
    .right {
      width: 100%;
      // margin: 0 20rpx;
      // background: pink;
    }
  }
}
</style>
